﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace VS.Commutil
{
   public  class ThumbImg
    {
        public Image ResourceImage;
        public string ErrMessage;

        public ThumbImg(Stream picStream) {
            ResourceImage = Image.FromStream(picStream);
            ErrMessage = "";
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        public bool GetReducedImage(int Width, int Height, string targetFilePath) {
            try
            {
                Image ReducedImage;

                int oldwidth = ResourceImage.Width;
                int oldheight = ResourceImage.Height;

                if (oldwidth > oldheight)
                {
                    Height = oldheight * Width / oldwidth;
                }
                else
                {
                    Width = oldwidth * Height / oldheight;
                }
                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
                ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);

                ReducedImage.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            } 
        }
    }
}
